package root.electronclass.electronclass.other

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.webkit.JavascriptInterface
import android.webkit.WebSettings
import androidx.core.os.bundleOf
import androidx.fragment.app.FragmentActivity
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import me.goldze.mvvmhabit.utils.KLog
import root.electronclass.electronclass.CommonActivity
import root.electronclass.electronclass.common.base.BasicDialogFragment
import root.electronclass.electronclass.common.base.CommonDialogFragment
import root.electronclass.electronclass.common.base.ViewBindingFragment
import root.electronclass.electronclass.common.util.ToastUtil
import root.electronclass.electronclass.databinding.FragmentWebBinding
import root.electronclass.electronclass.ext.startFragment
import root.electronclass.electronclass.grade.attendance.ClassAttendanceStatisticalFragment
import root.electronclass.electronclass.grade.curriculum.ClassCurriculumReasonDialog
import root.electronclass.electronclass.mvp.entity.FileData
import root.electronclass.electronclass.mvp.rest.RestManager
import root.electronclass.electronclass.personal.dialog.SchoolStudyDownDialog
import root.electronclass.electronclass.title


open class WebFragment : ViewBindingFragment<FragmentWebBinding>() {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        initX5WebView()
        loadUrl()
    }

    protected fun loadUrl(
        url: String? = arguments?.getString(EXTRA_DATA)?.let { it + "${if (it.contains("?")) "&" else "?"}token=${RestManager.getInstance().TOKEN}" }
    ) {
        setWeb(url ?: return)
//        binding.webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun setWeb(url: String) {
        Log.i("webActivity--url:", url)
        val webView = binding.webView
        webView.settings.javaScriptEnabled = true // 启用 JS
        webView.settings.domStorageEnabled = true // 启用 DOM Storage
        webView.settings.loadWithOverviewMode = true // 适应屏幕
        webView.settings.useWideViewPort = true
        webView.loadUrl(url)
        webView.webChromeClient = object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView?, title: String?) {
                val requireActivity = requireActivity()
                if (requireActivity is CommonActivity) {
                    requireActivity.binding.top.title(title ?: "")
                }
            }
        }
        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                //  重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
                Log.i("WebViewClient:", url)
                view.loadUrl(url)
                return true
            }

            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                KLog.i("webView ----- onPageStarted")
            }

            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                KLog.i("webView ----- onPageFinished")
            }

//            override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
//                handler?.proceed()
//            }
        }

        webView.addJavascriptInterface(object : Any() {

            //打开班级考勤历史记录
            @JavascriptInterface
            fun openAttendanceHistory() {
                startFragment(ClassAttendanceStatisticalFragment::class.java)

            }

            //打开签到原因
            @JavascriptInterface
            fun openSignReasonDialog(success: String, cancel: String) {
                ClassCurriculumReasonDialog().apply {
                    arguments = bundleOf(
                        BasicDialogFragment.TITLE to "课程签到",
                        BasicDialogFragment.OK to "提交",
                        BasicDialogFragment.CANCEL to "取消",
                    )
                    onCancelClick = {
                        webView.loadUrl("javascript:$cancel();")
                    }
                    onOkClick = {
                        webView.loadUrl("javascript:$success('${binding.edit.text.trim()}');")

                    }
                }.show(childFragmentManager, "CCSD")
            }

            //学习资料下载
            @JavascriptInterface
            fun openStudyDown(content: String) {
                Log.i("WebFragment", "openStudyDown: $content")
                startActivityForResult(Intent(requireActivity(), AttestationActivity::class.java), AttestationActivity.STUDYDOWN)
                val list: ArrayList<FileData> = Gson().fromJson(content, object : TypeToken<List<FileData?>?>() {}.type)
                SchoolStudyDownDialog().also {
                    it.arguments = bundleOf(
                        CommonDialogFragment.TITLE to "下载",
                        CommonDialogFragment.CLOSE to true,
                        CommonDialogFragment.CANCEL to "取消",
                        CommonDialogFragment.OK to "下载"

                    ).also { it.putParcelableArrayList(SchoolStudyDownDialog.DATA, list) }
                }.show(childFragmentManager, "STDD")
            }

            //关闭当前页
            @JavascriptInterface
            fun close() {
                requireActivity().finish()
            }

            //打开新界面
            @JavascriptInterface
            fun openNewWindow(url: String?) {
                startWeb(requireActivity(), url ?: return ToastUtil.showToast(requireActivity(), "url 为空"))
            }

            //打开身份认证
            @JavascriptInterface
            fun openAttestation() {
                startActivityForResult(Intent(requireActivity(), AttestationActivity::class.java), AttestationActivity.ATTESTATION)
            }

        }, "native")

        val displayMetrics = resources.displayMetrics
        displayMetrics.scaledDensity = 1f
        displayMetrics.density = 1f
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && data?.getBooleanExtra("SUCCESS",false) ?: false && requestCode == AttestationActivity.ATTESTATION) {
            binding.webView.loadUrl("javascript:attestationSuccess('${RestManager.getInstance().token}');")
        }
    }

    /**
     * 启用硬件加速
     */
    private  fun initX5WebView() {
        try {
            if (Build.VERSION.SDK.toInt() >= 11) {
                requireActivity().window.setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED)
            }
        } catch (e: Exception) {
        }
    }

    companion object {
        /**
         * 班级考勤:http://36.134.62.252:12310/dzbp/h5/class-attendance?departId=1955089771708313601
         * 班级签到:http://36.134.62.252:12310/dzbp/h5/seat-signin?departId=1955089771708313601
         * 班级座位编辑: http://36.134.62.252:12310/dzbp/h5/seat-edit?departId=1955089771708313601
         * 班级座位:http://36.134.62.252:12310/dzbp/h5/seat-management?departId=1955089771708313601
         * 班级通知:http://36.134.62.252:12310/dzbp/h5/class-notice?id=129
         */

        private const val BASE_URL = "http://36.134.62.252:12310/dzbp/h5/" //生产环境
//        private const val BASE_URL = "https://web.zf.zjbenti.com/dzbp/appweb/"//测试环境

        //校园通知
        const val SCHOOL_NOTIFICATION = "${BASE_URL}school-notice?id=%s"

        //班级通知
        const val CLASS_NOTIFICATION = "${BASE_URL}class-notice?id=%s"

        //校园学习空间
        const val SCHOOL_PROPAGANDA = "${BASE_URL}earningSpaceViews?id=%d"

        //班级座位
        const val CLASS_SEAT = "${BASE_URL}seat-management?departId=%d"

        //班级考勤
        const val CLASS_CHECK = "${BASE_URL}class-attendance?departId=%d"

        //班级课程签到
        const val CLASS_SIGN_IN = "${BASE_URL}seat-signin?departId=%d&timeId=%d"

        //应用中心--食堂
        const val APPLICATION_ST = "${BASE_URL}ecardApp/#/newcanteen?"

        //应用中心--校车申请
        const val APPLICATION_SCHOOLBUS = "${BASE_URL}schoolBus?"

        //应用中心--留校申请
        const val APPLICATION_STAYINSCHOOL = "${BASE_URL}stayInSchool?"

        //应用中心--心理咨询预约
        const val APPLICATION_PSYCHOLOGICAL = "${BASE_URL}psychological?"

        //应用中心--设备报修
        const val DEVICEMANAGEMENT = "${BASE_URL}deviceManagement?"

        //应用中心--学生请假
        const val LEAVE = "${BASE_URL}leave?"

        //应用中心--考场模式（无需刷卡直接传设备token）
        const val EXAMINATIONROOM = "${BASE_URL}examinationRoom?"

        //应用中心--智慧食堂
        const val NEWCANTEEN = "${BASE_URL}newcanteen?"

        //应用中心--请假总览
        const val LEAVESTATS = "${BASE_URL}leavestats?"

        //应用中心--综合素质评价（无需刷卡直接传设备token）
        const val ZHSZPJ = "${BASE_URL}comprehensiveQualityEvaluation?"


        /**
         * 启动网页
         */
        @JvmStatic
        fun startWeb(context: FragmentActivity, url: String) {
            context.startFragment(WebFragment::class.java, bundleOf(EXTRA_DATA to url))
        }
    }


}